<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    if (isset($_GET['email']) && isset($_GET['nonce'])) {
        include_once("db_connection.php");
        $conn = getdb();
        $stmt = $conn->prepare("UPDATE resets SET active=0 WHERE email=:email AND nonce=:nonce");
        $stmt->bindParam(':email', $_GET['email']);
        $stmt->bindParam(':nonce', $_GET['nonce']);
        $stmt->execute();

        $affectRows = $stmt->rowCount();
        if ($affectRows > 0) {
            $_SESSION['change_pass_email'] = $_GET['email'];
            refreshChangePassToken();
            require_once("change_password_form.php");
        } else {
            failGet("Invalid reset link!");
        }

    } else {
        failGet("Bye");
    }
} elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['password'])) {
        if (!isset($_POST['change_pass_token']) || $_POST['change_pass_token'] != $_SESSION['change_pass_token']) {
            failPost("Invalid token!");
        }
        refreshChangePassToken();
        include_once("auth_process.php");
        $email = $_SESSION['change_pass_email'];
        $password = $_POST['password'];

        require_once("validator.php");
        if (!validateEmail($email)) {
            failPost("Invalid email pattern");
        }
        if (!validatePassword($password)) {
            failPost("Invalid password pattern");
        }


        $user = getUserByEmail($email);

        $pass_hash = hash_hmac("sha256", $password, $user['salt']);

        include_once("db_connection.php");
        $conn = getdb();
        $stmt = $conn->prepare("UPDATE users SET pass_hash=:pass_hash WHERE email=:email");
        $stmt->bindParam(':email', $email);
        $stmt->bindParam(':pass_hash', $pass_hash);
        $stmt->execute();

        echo "<script>alert(\"Change password successfully!\"); window.location.href=\"login.php\"</script>";
    }
}


function failGet($msg)
{
    echo "<script>alert(\"Sorry ! {$msg}\"); window.location.href=\"reset_password.php\"</script>";
    exit();
}

function failPost($msg)
{
    echo "<script>alert(\"Sorry ! {$msg} . Due to security problem, please reset your password through the workflow again.\"); window.location.href=\"reset_password.php\"</script>";
    exit();
}

function refreshChangePassToken()
{
    $change_pass_token = md5(time() . "change_pass_token" . rand(0, 9999));
    $_SESSION['change_pass_token'] = $change_pass_token;
}